document.addEventListener('DOMContentLoaded', function() {
    // 按钮监听
    document.querySelectorAll('.edit-question').forEach(button => {
        button.addEventListener('click', function() {
            const id = this.dataset.id;
            const content = this.dataset.content;
            const answer = this.dataset.answer;
            editQuestion(id, content, answer);
        });
    });

    // 删除按钮监听
    document.querySelectorAll('.delete-question').forEach(button => {
        button.addEventListener('click', function() {
            const id = this.dataset.id;
            deleteQuestion(id);
        });
    });

    //选择所有
    document.getElementById('selectAll').addEventListener('change', function() {
        const checkboxes = document.querySelectorAll('.question-checkbox');
        checkboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
        });
        updateBatchDeleteButton();
    });

    //
    document.querySelectorAll('.question-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', updateBatchDeleteButton);
    });

    // 搜索
    document.getElementById('searchBtn').addEventListener('click', searchQuestions);
    document.getElementById('searchInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            searchQuestions();
        }
    });

    // 删除按钮
    document.getElementById('batchDeleteBtn').addEventListener('click', batchDelete);
});

function updateBatchDeleteButton() {
    const checkedBoxes = document.querySelectorAll('.question-checkbox:checked');
    document.getElementById('batchDeleteBtn').disabled = checkedBoxes.length === 0;
}

function searchQuestions() {
    const searchTerm = document.getElementById('searchInput').value.trim();
    fetch(`/admin/api/questions/search?q=${encodeURIComponent(searchTerm)}`)
        .then(response => response.json())
        .then(data => {
            const tbody = document.getElementById('questionsTableBody');
            tbody.innerHTML = '';

            data.questions.forEach(question => {
                const tr = document.createElement('tr');
                tr.innerHTML = `
                    <td>
                        <div class="form-check">
                            <input class="form-check-input question-checkbox" type="checkbox" value="${question.id}">
                        </div>
                    </td>
                    <td>${question.id}</td>
                    <td>${question.content}</td>
                    <td>${question.answer}</td>
                    <td>${question.create_time}</td>
                    <td>
                        <button type="button" class="btn btn-sm btn-primary me-2 edit-question" 
                                data-id="${question.id}"
                                data-content="${question.content.replace(/'/g, "\\'")}"
                                data-answer="${question.answer.replace(/'/g, "\\'")}">
                            <i class="bi bi-pencil"></i>
                        </button>
                        <button type="button" class="btn btn-sm btn-danger delete-question" 
                                data-id="${question.id}">
                            <i class="bi bi-trash"></i>
                        </button>
                    </td>
                `;
                tbody.appendChild(tr);
            });

            // Reattach event listeners
            document.querySelectorAll('.edit-question').forEach(button => {
                button.addEventListener('click', function() {
                    const id = this.dataset.id;
                    const content = this.dataset.content;
                    const answer = this.dataset.answer;
                    editQuestion(id, content, answer);
                });
            });

            document.querySelectorAll('.delete-question').forEach(button => {
                button.addEventListener('click', function() {
                    const id = this.dataset.id;
                    deleteQuestion(id);
                });
            });

            document.querySelectorAll('.question-checkbox').forEach(checkbox => {
                checkbox.addEventListener('change', updateBatchDeleteButton);
            });
        })
        .catch(error => {
            console.error('Error:', error);
            alert('搜索失败');
        });
}

// 初始化模态框
const successModal = new bootstrap.Modal(document.getElementById('successModal'));
const errorModal = new bootstrap.Modal(document.getElementById('errorModal'));

function showSuccess(title, message) {
    $('#successTitle').text(title);
    $('#successMessage').text(message);
    successModal.show();
}

function showError(message) {
    $('#errorMessage').text(message);
    errorModal.show();
}

function addQuestion() {
    const form = document.getElementById('addQuestionForm');
    const formData = new FormData(form);
    const data = {
        content: formData.get('content'),
        answer: formData.get('answer')
    };

    fetch('/admin/api/questions', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            showError(data.error);
        } else {
            showSuccess('添加成功', '题目已成功添加到题库中。');
            location.reload();
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showError('添加题目失败');
    });
}

function editQuestion(id, content, answer) {
    document.getElementById('edit_id').value = id;
    document.getElementById('edit_content').value = content;
    document.getElementById('edit_answer').value = answer;
    new bootstrap.Modal(document.getElementById('editQuestionModal')).show();
}

function updateQuestion() {
    const form = document.getElementById('editQuestionForm');
    const formData = new FormData(form);
    const data = {
        id: formData.get('id'),
        content: formData.get('content'),
        answer: formData.get('answer')
    };

    fetch(`/admin/api/questions/${data.id}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            alert(data.error);
        } else {
            location.reload();
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('更新题目失败');
    });
}

function deleteQuestion(id) {
    if (confirm('确定要删除这道题目吗？')) {
        fetch(`/admin/api/questions/${id}`, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                showError(data.error);
            } else {
                showSuccess('删除成功', '题目已成功删除。');
                location.reload();
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showError('删除题目失败');
        });
    }
}

function importQuestions() {
    const form = document.getElementById('importForm');
    const formData = new FormData(form);

    fetch('/admin/api/questions/import', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            showError(data.error);
        } else {
            showSuccess('导入成功', '题目已成功导入到题库中。');
            location.reload();
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showError('导入题目失败');
    });
}

function batchDelete() {
    const checkedBoxes = document.querySelectorAll('.question-checkbox:checked');
    const ids = Array.from(checkedBoxes).map(checkbox => checkbox.value);

    if (ids.length === 0) {
        showError('请选择要删除的题目');
        return;
    }

    document.getElementById('deleteCount').textContent = ids.length;
    const modal = new bootstrap.Modal(document.getElementById('batchDeleteModal'));
    modal.show();

    document.getElementById('confirmBatchDelete').onclick = function() {
        fetch('/admin/api/questions/batch-delete', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ ids: ids })
        })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                showError(data.error);
            } else {
                showSuccess('删除成功', '选中的题目已成功删除。');
                location.reload();
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showError('批量删除失败');
        });

        modal.hide();
    };
}

function exportQuestions() {
    fetch('/admin/api/questions/export')
        .then(response => {
            if (!response.ok) {
                throw new Error('导出失败');
            }
            return response.blob();
        })
        .then(blob => {
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'questions.xlsx';
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
            showSuccess('导出成功', '题目已成功导出到Excel文件。');
        })
        .catch(error => {
            console.error('Error:', error);
            showError('导出题目失败');
        });
}